import CryptoJS from 'crypto-js'

// 生成签名
export function getSignature({ secretId, secretKey, host, service, action, version }) {
  const timestamp = Math.floor(Date.now() / 1000)
  const date = getDate(timestamp)
  const payload = "{}"
  
  // 步骤1：拼接规范请求串
  const signedHeaders = "content-type;host"
  const hashedRequestPayload = getHash(payload)
  const httpRequestMethod = "POST"
  const canonicalUri = "/"
  const canonicalQueryString = ""
  const canonicalHeaders = `content-type:application/json; charset=utf-8\nhost:${host}\n`
  
  const canonicalRequest = `${httpRequestMethod}\n${canonicalUri}\n${canonicalQueryString}\n${canonicalHeaders}\n${signedHeaders}\n${hashedRequestPayload}`
  
  // 步骤2：拼接待签名字符串
  const algorithm = "TC3-HMAC-SHA256"
  const hashedCanonicalRequest = getHash(canonicalRequest)
  const credentialScope = `${date}/${service}/tc3_request`
  const stringToSign = `${algorithm}\n${timestamp}\n${credentialScope}\n${hashedCanonicalRequest}`
  
  // 步骤3：计算签名
  const kDate = hmacSHA256(date, "TC3" + secretKey)
  const kService = hmacSHA256(service, kDate)
  const kSigning = hmacSHA256("tc3_request", kService)
  const signature = hmacSHA256(stringToSign, kSigning)
  
  // 步骤4：拼接 Authorization
  return `${algorithm} Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
}

// 获取日期
function getDate(timestamp) {
  const date = new Date(timestamp * 1000)
  const year = date.getUTCFullYear()
  const month = ("0" + (date.getUTCMonth() + 1)).slice(-2)
  const day = ("0" + date.getUTCDate()).slice(-2)
  return `${year}-${month}-${day}`
}

// 计算 SHA256 哈希
function getHash(message) {
  return CryptoJS.SHA256(message).toString()
}

// 计算 HMAC-SHA256
function hmacSHA256(message, key) {
  return CryptoJS.HmacSHA256(message, key).toString()
} 